package com.example.myapplication.ui.movie

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.android_program.data_class.movie_2_2
import com.example.android_program.data_class.movie_2_3
import com.example.myapplication.MovieDetailsActivity
import com.example.myapplication.R
import kotlinx.android.synthetic.main.fragment_movie_tobeshown.*
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONArray
import java.lang.Exception
import java.lang.StringBuilder
import java.lang.reflect.Field
import java.net.URLEncoder
import kotlin.concurrent.thread

//待映
public class ToBeShownFragment : Fragment() {

    val movie_Notice_Src: ArrayList<movie_2_3> = ArrayList()
    val movie_Notice_innfo: ArrayList<movie_2_2> = ArrayList()
    val sever_ip = "192.168.43.8"

    val showAll_ToBeShown_jsp = "http://${sever_ip}:8080/JspForAndroid/showAll_ToBeShown.jsp"
    val showAll_ToBeShownHead_jsp = "http://${sever_ip}:8080/JspForAndroid/showAll_ToBeShownHead.jsp"
//    val showAll_ToBeShown_jsp = "http://${resources.getString(R.string.sever_ip)}:8080/JspForAndroid/showAll_ToBeShown.jsp"
//    val showAll_ToBeShownHead_jsp = "http://${resources.getString(R.string.sever_ip)}:8080/JspForAndroid/showAll_ToBeShownHead.jsp"

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        val root = inflater.inflate(R.layout.fragment_movie_tobeshown, container, false)

        return root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        Recycler_data_1_2()
        Recycler_1_2_initView()

        /*Turnto.setOnClickListener {
            startActivity(Intent(context, SelectCinemaActivity::class.java))
        }*/
    }

    //---------------------------------------------------------------------------------------------
    private fun Recycler_1_2_initView() {
        val layoutManager5 = LinearLayoutManager( context)
        layoutManager5.orientation = LinearLayoutManager.HORIZONTAL
        myrecyclerview5.layoutManager = layoutManager5
        val adapter5 = MovieAapter5(movie_Notice_Src)
        myrecyclerview5.adapter = adapter5

        val layoutManager4 = LinearLayoutManager( context)
        myrecyclerview4.layoutManager = layoutManager4
        val adapter4 = MovieAapter4(movie_Notice_innfo, this.requireContext())
        myrecyclerview4.adapter = adapter4
    }

    fun Recycler_data_1_2() {  //列表数据加载

        //初始化轮播图
        getAllTrainInfoJson2()
        //初始化列表
        getAllTrainInfoJson()

    }
    //1-----
    private class movieViewHolder_2_2(view: View) : RecyclerView.ViewHolder(view) {
        var movie2_img2: ImageView = view.findViewById(R.id.movie2_img2)
        var movie2_infoSrc: ImageView = view.findViewById(R.id.movie2_infoSrc)
        var goupiao_3_2: ImageView = view.findViewById(R.id.goupiao_3_2)
    }
    //适配器
    private class MovieAapter4(val movie_Notice_innfo: List<movie_2_2>, val context: Context):
        RecyclerView.Adapter<movieViewHolder_2_2>() {
        //Ctrl+o
        //创建视图
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): movieViewHolder_2_2 {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.layout_movie_2_2, parent, false)
            //点击事件  获取点击的  list 中的数据
            val viewHolder = movieViewHolder_2_2(view)
            view.setOnClickListener {
                val position = viewHolder.adapterPosition
                val info = movie_Notice_innfo[position]
                Toast.makeText(parent.context,"电影图片", Toast.LENGTH_LONG).show()
                val mIntent = Intent(context, MovieDetailsActivity::class.java)
                mIntent.putExtra("movie_name", info.movie2_name2)//可能要改进
                mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
                context.startActivity(mIntent)
            }
            viewHolder.goupiao_3_2.setOnClickListener {
                val position = viewHolder.adapterPosition
                val info = movie_Notice_innfo[position]

                if (info.movie2_wanted == "true") {
                    info.movie2_wanted = "false"
                    viewHolder.goupiao_3_2.setImageResource(R.drawable.p4)
                    Toast.makeText(parent.context,"已取消想看", Toast.LENGTH_LONG).show()
                    getAllTrainInfoJson4(info.movie2_src2)
                }
                else {
                    info.movie2_wanted = "true"
                    viewHolder.goupiao_3_2.setImageResource(R.drawable.p6)
                    Toast.makeText(parent.context,"已加入想看", Toast.LENGTH_LONG).show()
                    getAllTrainInfoJson3(info.movie2_src2)
                }
            }
            return viewHolder
        }
        //绑定数据
        override fun onBindViewHolder(holder: movieViewHolder_2_2, position: Int) {
            val info = movie_Notice_innfo[position]
            holder.movie2_img2.setImageResource(info.movie2_src2)
            holder.movie2_infoSrc.setImageResource(info.movie2_info2)

            if (info.movie2_wanted == "true")
                holder.goupiao_3_2.setImageResource(R.drawable.p6)
            else
                holder.goupiao_3_2.setImageResource(R.drawable.p4)

        }
        //获取列表行数
        override fun getItemCount(): Int {
            return movie_Notice_innfo.size
        }
        private fun getAllTrainInfoJson3(wanted_movie_src:Int){
            val sever_ip = "192.168.43.8"
            val addWantedMoive = "http://${sever_ip}:8080/JspForAndroid/addWantedMovie.jsp"
            //val addWantedMoive = "http://${context.getString(R.string.sever_ip)}:8080/JspForAndroid/addWantedMovie.jsp"
            thread {
                try {
                    val client = OkHttpClient()
                    val movie_src = wanted_movie_src.toString()

                    val requestBody = FormBody.Builder()
                        .add("wanted_movie_src", URLEncoder.encode(movie_src,"UTF-8"))
                        .build()

                    //构建请求
                    val request = Request.Builder()
                        .url(addWantedMoive)
                        .post(requestBody)
                        .build()
                    //执行
                    client.newCall(request).execute()
                    //得到返回值

                }catch (e: Exception){
                    e.printStackTrace()
                }
            }
        }
        private fun getAllTrainInfoJson4(wanted_movie_src:Int){
            val sever_ip = "192.168.43.8"
            val deleteWantedMoive = "http://${sever_ip}:8080/JspForAndroid/deleteWantedMovie.jsp"
            //val deleteWantedMoive = "http://${context.getString(R.string.sever_ip)}:8080/JspForAndroid/deleteWantedMovie.jsp"
            thread {
                try {
                    val client = OkHttpClient()
                    val movie_src = wanted_movie_src.toString()

                    val requestBody = FormBody.Builder()
                        .add("wanted_movie_src", URLEncoder.encode(movie_src,"UTF-8"))
                        .build()

                    //构建请求
                    val request = Request.Builder()
                        .url(deleteWantedMoive)
                        .post(requestBody)
                        .build()
                    //执行
                    client.newCall(request).execute()
                    //得到返回值

                }catch (e: Exception){
                    e.printStackTrace()
                }
            }
        }

    }
    //2-----
    private class movieViewHolder2_3(view: View) : RecyclerView.ViewHolder(view) {
        var movie_Notice_Src: ImageView = view.findViewById(R.id.movie_Notice_Src)
    }
    //适配器
    private class MovieAapter5(val movie_Notice_Src: List<movie_2_3>): RecyclerView.Adapter<movieViewHolder2_3>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): movieViewHolder2_3 {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.layout_movie_2_3, parent, false)
            //点击事件
            val viewHolder = movieViewHolder2_3(view)
            viewHolder.movie_Notice_Src.setOnClickListener {
                val position = viewHolder.adapterPosition
                val info = movie_Notice_Src[position]
                Toast.makeText(parent.context,"电影预告片", Toast.LENGTH_LONG).show()
            }
            return viewHolder
        }
        //绑定数据
        override fun onBindViewHolder(holder: movieViewHolder2_3, position: Int) {
            val info = movie_Notice_Src[position]
            holder.movie_Notice_Src.setImageResource(info.movie2_3_Src)
        }
        //获取列表行数
        override fun getItemCount(): Int {
            return movie_Notice_Src.size
        }
    }

    //json解析
    private fun getAllTrainInfoJson(){
        thread {
            try {
                val client = OkHttpClient()

                //构建请求
                val request = Request.Builder()
                    .url(showAll_ToBeShown_jsp)
                    .build()
                //执行
                val response= client.newCall(request).execute()
                //得到返回值
                val responseData = response.body?.string()
//                txtData.text = responseData
                val result = parseJson(responseData)
                if (responseData != null){
                    activity?.runOnUiThread{
                        //修改布局
                        // txtData.text = result

                        val layoutManager4 = LinearLayoutManager( context)
                        myrecyclerview4.layoutManager = layoutManager4
                        val adapter4 = MovieAapter4(movie_Notice_innfo, this.requireContext())
                        myrecyclerview4.adapter = adapter4
                    }
                }
            }catch (e: Exception){
                e.printStackTrace()
            }
        }
    }
    private fun parseJson(jsonData:String?):String{
        val builder = StringBuilder()
        try {
            //json数组

            val jsonArray = JSONArray(jsonData)
            //清空原来的子项
            movie_Notice_innfo.clear()
            //向列表中加入子项
            for (i in 0 until jsonArray.length()){
                //取出元素
                val jsonObject = jsonArray.getJSONObject(i)
                val movie_src = jsonObject.optString("movie_src")
                val movie_info_src = jsonObject.optString("movie_info_src")
                val movie_name = jsonObject.optString("movie_name")
                val movie_wanted = jsonObject.optString("movie_wanted")
                //builder.append("$movie_name--$movie_src--$movie_score--$movie_kind, ")
                movie_Notice_innfo.add(
                    movie_2_2(getResourceIdByString(movie_src), getResourceIdByString(movie_info_src), movie_name
                    ,movie_wanted)
                )
            }
        }catch (e: Exception){
            e.printStackTrace()
        }

        return builder.toString()
    }

    private fun getAllTrainInfoJson2(){
        thread {
            try {
                val client = OkHttpClient()

                //构建请求
                val request = Request.Builder()
                    .url(showAll_ToBeShownHead_jsp)
                    .build()
                //执行
                val response= client.newCall(request).execute()
                //得到返回值
                val responseData = response.body?.string()
//                txtData.text = responseData
                val result = parseJson2(responseData)
                if (responseData != null){
                    activity?.runOnUiThread{
                        //修改布局
                        // txtData.text = result

                        val layoutManager5 = LinearLayoutManager( context)
                        layoutManager5.orientation = LinearLayoutManager.HORIZONTAL
                        myrecyclerview5.layoutManager = layoutManager5
                        val adapter5 = MovieAapter5(movie_Notice_Src)
                        myrecyclerview5.adapter = adapter5
                    }
                }
            }catch (e: Exception){
                e.printStackTrace()
            }
        }
    }
    private fun parseJson2(jsonData:String?):String{
        val builder = StringBuilder()
        try {
            //json数组

            val jsonArray = JSONArray(jsonData)
            //清空原来的子项
            movie_Notice_Src.clear()
            //向列表中加入子项
            for (i in 0 until jsonArray.length()){
                //取出元素
                val jsonObject = jsonArray.getJSONObject(i)
                val movie_notice_src = jsonObject.getString("movie_notice_src")

                //builder.append("$movie_name--$movie_src--$movie_score--$movie_kind, ")
                movie_Notice_Src.add(
                    movie_2_3(getResourceIdByString(movie_notice_src))
                )
            }
        }catch (e: Exception){
            e.printStackTrace()
        }

        return builder.toString()
    }


    private fun getResourceIdByString(s: String?): Int {
        try {
            val field: Field = R.drawable::class.java.getField(s)
            return field[null].toString().toInt()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return 0
    }
}